﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using DGMResourcesTool.Logic;
using DGMResourcesTool.Logic.Config;
using DGMResourcesTool.Logic.FileUtil;
using DGMResourcesTool.Logic.P4Util;

namespace DGMResourcesTool
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private static readonly string Path_Config_Name = "path_config.txt"; // 基础路径配置.
        private PathConfigData _pathConfigData = new PathConfigData();  // 配置路径.
        private string _resFilePath = string.Empty;                     // 需要查找的ab资源路径.
        private string _resFileSourcePath = String.Empty;               // ab资源对应的原始资源路径.
        private string _newActivityPath = string.Empty;                 // ab资源对应的第二个原始资源路径.
        private string _p4FilePath = string.Empty;                      // 单个操作的p4文件路径.
        private EnumResType _batchResType;                              // 批量查找资源类型.
        private EnumP4FileType _singleP4FileType;                       // 单个操作p4文件类型.
        private Dictionary<string, string> _dstContents = new Dictionary<string, string>(); // 目标文件库存.
        private Dictionary<string, string> _activityDstContents = new Dictionary<string, string>();

        private LoadingWindow _loadingWindow;
        private BackgroundWorker _bgWorker;
        public MainWindow()
        {
            InitializeComponent();
            InitData();

            PathConfigData pathConfigData = GetPathConfig();
            if (pathConfigData == null)
            {
                LogUtility.AddToLog(Path_Config_Name + "配置表格式错误！！！");
                LogUtility.AddToLog("功能无法正常使用！！！");
                return;
            }
            T_UIPefabPath.Text = pathConfigData.m_UIPrefabPath;
            T_ScriptsPath.Text = pathConfigData.m_ScriptsPath;
            T_ClientPath.Text = pathConfigData.m_ClientCfgPath;
            T_ServerPath.Text = pathConfigData.m_ServerCfgPath;
        }

        private void InitData()
        {
            FilterConfigUtility.ReadFilter();
        }

        protected override void OnClosed(EventArgs e)
        {
            _loadingWindow?.Close();
            _bgWorker?.CancelAsync();
        }

        #region 基础路径配置

        /// <summary>
        /// 从文件读取p4参数.
        /// </summary>
        private PathConfigData GetPathConfig()
        {
            string filePath = FileUtility.GetConfigFilePath(Path_Config_Name);
            string[] lines = FileReaderWriterUtility.ReadFile(filePath, Encoding.UTF8);
            if (lines.Length == 4)
            {
                _pathConfigData = new PathConfigData();
                _pathConfigData.m_UIPrefabPath = lines[0].Split('#')[1];
                _pathConfigData.m_ScriptsPath = lines[1].Split('#')[1];
                _pathConfigData.m_ServerCfgPath = lines[2].Split('#')[1];
                _pathConfigData.m_ClientCfgPath = lines[3].Split('#')[1];
                return _pathConfigData;
            }
            return null;
        }

        #endregion

        #region 批量查找

        /// <summary>
        /// 要批量查找的资源路径变化.
        /// </summary>
        private void T_ResPath_TextChanged(object sender, EventArgs e)
        {
            _resFilePath = T_ResPath.Text;
        }

        /// <summary>
        /// 要查找的AB资源对应的原始资源根目录.
        /// </summary>
        private void T_SourceResPath_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (_batchResType == EnumResType.Animation)
            {
                return;
            }
            _resFileSourcePath = T_SourceResPath.Text;
        }

        private void T_SourceResPath_TextChanged2(object sender, TextChangedEventArgs e)
        {
            if (_batchResType == EnumResType.Animation)
            {
                return;
            }
            _newActivityPath = T_NewActivityPath.Text;
        }

        /// <summary>
        /// 批量查找单选按钮选择.
        /// </summary>
        private void BatchResToggleButton_OnChecked(object sender, RoutedEventArgs e)
        {
            RadioButton radioButton = (RadioButton) sender;
            if (radioButton.IsChecked != null && radioButton.IsChecked == true)
            {
                _batchResType = (EnumResType) Int32.Parse(radioButton.Tag.ToString());
            }

            if (_batchResType == EnumResType.Animation)
            {
                T_SourceResPath.IsEnabled = false;
                T_SourceResPath.Text = "此AB源文件不在Resource\\art_src目录下.不会自动打包到ab目录。无需删除。";
                T_NewActivityPath.IsEnabled = false;
                T_NewActivityPath.Text = "此AB源文件不在Resource\\art_src目录下.不会自动打包到ab目录。无需删除。";
            }
            else
            {
                T_SourceResPath.IsEnabled = true;
                T_SourceResPath.Text = _resFileSourcePath;
                T_NewActivityPath.IsEnabled = true;
                T_NewActivityPath.Text = _newActivityPath;
            }
        }

        #region 检测没有原始文件的资源列表

        /// <summary>
        /// 搜索没有原始文件的资源列表.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BTN_Scan_No_Original_File_Resources(object sender, EventArgs e)
        {
            if (!CheckRamData())
            {
                return;
            }
            _bgWorker = new BackgroundWorker();
            _bgWorker.DoWork += BGWorker_DoScanNoOriginalFileWork;
            _bgWorker.WorkerReportsProgress = true;
            _bgWorker.ProgressChanged += BGWorker_ProgressChanged;
            _bgWorker.RunWorkerAsync();
        }

        private void BGWorker_DoScanNoOriginalFileWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bgWorker = sender as BackgroundWorker;
            ShowLoadingWindow();

            DateTime begionTime = DateTime.Now;
            List<ResFileInfo> resFileInf = new List<ResFileInfo>(50000);

            FillResFileInfoList(resFileInf);

            List<ResFileInfo> unUseResFileInfos = new List<ResFileInfo>();
            if (resFileInf.Count > 0)
            {
                int i = 0;
                foreach (ResFileInfo r in resFileInf)
                {
                    ++i;

                    // 设置进度.
                    SetProgressStr(i, resFileInf.Count, bgWorker);
                    if (r.SourceFullPath == "无")
                    {
                        unUseResFileInfos.Add(r);
                    }
                }

                if (unUseResFileInfos.Count > 0)
                {
                    WriteResFileInfoToCSV(EnumScanType.NoOriginalFileResource, unUseResFileInfos);
                }
            }

            if (System.Threading.Thread.CurrentThread != this.Dispatcher.Thread)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    if (resFileInf.Count == 0)
                    {
                        BTN_Scan_No_Original_File.IsEnabled = true;
                        _loadingWindow.Close();
                    }

                    if (unUseResFileInfos.Count == 0)
                    {
                        LogUtility.AddToLog("没有检测到任何无用资源！");
                    }
                    DateTime endTime = DateTime.Now;
                    TimeSpan costTimeSpan = endTime.Subtract(begionTime);
                    string costTime = costTimeSpan.ToString().Substring(0, 8);
                    LogUtility.AddToLog("总用时：" + costTime);
                });
            }
        }

        #endregion

        /// <summary>
        /// 扫描文件,并且输出到CSV.
        /// </summary>
        private void BTN_Scan_Click(object sender, EventArgs e)
        {
            
            if (!CheckRamData())
            {
                return;
            }

            _bgWorker = new BackgroundWorker();
            _bgWorker.DoWork += BGWorker_DoScanWork;
            _bgWorker.WorkerReportsProgress = true;
            _bgWorker.ProgressChanged += BGWorker_ProgressChanged;
            _bgWorker.RunWorkerAsync();
        }

        private void BGWorker_DoScanWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bgWorker = sender as BackgroundWorker;
            ShowLoadingWindow();

            DateTime begionTime = DateTime.Now;
            List<ResFileInfo> resFileInf = new List<ResFileInfo>(50000);

            FillResFileInfoList(resFileInf);

            List<ResFileInfo> unUseResFileInfos = new List<ResFileInfo>();
            if (resFileInf.Count > 0)
            {
                int i = 0;
                foreach (ResFileInfo r in resFileInf)
                {
                    ++i;

                    // 设置进度.
                    SetProgressStr(i, resFileInf.Count, bgWorker);
                    bool isUsed = false;

                    if (FilterConfigUtility.IsIgnore(r))
                    {
                        continue;
                    }

                    isUsed = CheckResFileIsUsed(r);
                    if (!isUsed)
                    {
                        unUseResFileInfos.Add(r);
                    }
                }

                if (unUseResFileInfos.Count > 0)
                {
                    WriteResFileInfoToCSV(EnumScanType.NoReferenceResource, unUseResFileInfos);
                }
            }
            
            if (System.Threading.Thread.CurrentThread != this.Dispatcher.Thread)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    if (resFileInf.Count == 0)
                    {
                        BTN_Scan.IsEnabled = true;
                        _loadingWindow.Close();
                    }

                    if (unUseResFileInfos.Count == 0)
                    {
                        LogUtility.AddToLog("没有检测到任何无用资源！");
                    }
                    DateTime endTime = DateTime.Now;
                    TimeSpan costTimeSpan = endTime.Subtract(begionTime);
                    string costTime = costTimeSpan.ToString().Substring(0, 8);
                    LogUtility.AddToLog("总用时：" + costTime);
                });
            }
        }

        /// <summary>
        /// 设置进度条进度.
        /// </summary>
        private static void SetProgressStr(int i, int total, BackgroundWorker bgWorker)
        {
            int progress = (int) (i / (float)total * 100);
            string fileProgress = "(" + i + "/" + total + ")";
            bgWorker.ReportProgress(progress, fileProgress);
        }

        /// <summary>
        /// 检查资源是否用到.
        /// </summary>
        private bool CheckResFileIsUsed(ResFileInfo r)
        {
            bool isUsed = false;
            foreach (var kv in _dstContents)
            {
                if (kv.Value.Contains(r.Name))
                {
                    isUsed = true;
                    continue;
                }

                if (!string.IsNullOrEmpty(r.ProcessdName) && kv.Value.Contains(r.ProcessdName))
                {
                    isUsed = true;
                    continue;
                }
            }

            return isUsed;
        }

        /// <summary>
        /// 填充List<ResFileInfo>
        /// </summary>
        /// <param name="resFileInf"></param>
        private void FillResFileInfoList(List<ResFileInfo> resFileInf)
        {
            string[] files = System.IO.Directory.GetFiles(_resFilePath, "*", System.IO.SearchOption.AllDirectories);
            foreach (string f in files)
            {
                if (f.EndsWith("h3dmanifest"))
                {
                    continue;
                }

                ResFileInfo rfi = new ResFileInfo();
                rfi.Init(f);
                // 获取ab资源大小.
                rfi.Size = FileReaderWriterUtility.GetFileKBSize(f).ToString();
                // 获取ab资源对应的原始资源路径.
                string sourceFullPath = GetSourceFullPathByABFullPath(f);
                if (!string.IsNullOrEmpty(sourceFullPath))
                {
                    rfi.SourceFullPath = sourceFullPath;
                }
                else
                {
                    rfi.SourceFullPath = "无";
                }

                if (rfi.Name.StartsWith("0000000101_"))
                {
                    continue;
                }

                if (rfi.Name.StartsWith("1000000101_"))
                {
                    continue;
                }

                resFileInf.Add(rfi);
            }
        }

        /// <summary>
        /// 现实loading.
        /// </summary>
        private void ShowLoadingWindow()
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                BTN_Scan.IsEnabled = false;
                _loadingWindow = new LoadingWindow();
                _loadingWindow.Show();
                _loadingWindow.SetProgressValue(0);
            });
        }

        private void BGWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //修改进度条的显示。
            _loadingWindow.SetProgressValue(e.ProgressPercentage);
            _loadingWindow.SetProgressLabel(e.ProgressPercentage + "%" + e.UserState);
            if (e.ProgressPercentage == 100)
            {
                BTN_Scan.IsEnabled = true;
                _loadingWindow.Close();
            }
        }

        /// <summary>
        /// 根据ab资源路径,获取到原始资源的路径.
        /// </summary>
        /// <returns></returns>
        private string GetSourceFullPathByABFullPath(string abFullPath)
        {
            string temppath = _resFileSourcePath;
            if (abFullPath.Contains(_resFilePath))
            {
                string relativePath = abFullPath.Remove(0, _resFilePath.Length);
                temppath += relativePath;
            }

            if (temppath.EndsWith("_mat"))
            {
                temppath = temppath.Remove(temppath.Length - 4, 4);
            }

            if (FileUtility.GetFilePathWithExtension(_batchResType, ref temppath))
            {
                return temppath;
            }

            return GetActivitySourceFullPathByABFullPath(abFullPath);
        }

        private string GetActivitySourceFullPathByABFullPath(string abFullPath)
        {
            string[] subdirectoryEntries = Directory.GetDirectories(_newActivityPath);
            for (int i = 0; i < subdirectoryEntries.Length; i++)
            {
                string temppath = subdirectoryEntries[i];
                if (abFullPath.Contains(_resFilePath))
                {
                    string relativePath = abFullPath.Remove(0, _resFilePath.Length);
                    temppath += relativePath;
                }

                if (temppath.EndsWith("_mat"))
                {
                    temppath = temppath.Remove(temppath.Length - 4, 4);
                }

                if (FileUtility.GetFilePathWithExtension(_batchResType, ref temppath))
                {
                    return temppath;
                }
            }

            return string.Empty;
        }

        /// <summary>
        /// 将资源数据列表写入CSV.
        /// </summary>
        private void WriteResFileInfoToCSV(EnumScanType enumScanType, List<ResFileInfo> fileInfos)
        {
            string[] strs = new[] { "ab路径", "texture路径", "ab资源大小" };
            List<string[]> strList = new List<string[]>();
            strList.Add(strs);
            foreach (var fileInfo in fileInfos)
            {
                string[] tempStrings = new[] { fileInfo.FullPath, fileInfo.SourceFullPath, fileInfo.Size };
                strList.Add(tempStrings);
            }

            string csvFilePath = FileUtility.GetConfigFilePath(GetOutPutCSVFileName(enumScanType, _batchResType), true);
            if (!FileReaderWriterUtility.WriteToCSV(csvFilePath, strList))
            {
                if (System.Threading.Thread.CurrentThread != this.Dispatcher.Thread)
                {
                    Application.Current.Dispatcher.Invoke(() => { LogUtility.AddToLog("写入csv失败！！！"); });
                }
            }
            else
            {
                if (System.Threading.Thread.CurrentThread != this.Dispatcher.Thread)
                {
                    Application.Current.Dispatcher.Invoke(() => { LogUtility.AddToLog("写入" + csvFilePath + "成功！！！"); });
                }
            }
        }

        /// <summary>
        /// 根据类型获取输出的CSV文件名称.
        /// </summary>
        /// <returns></returns>
        private string GetOutPutCSVFileName(EnumScanType scanType, EnumResType resType)
        {
            string time = DateTime.Now.ToString("MM_dd_HH_mm_ss");
            string prefix = string.Empty;
            switch (scanType)
            {
                case EnumScanType.Invalid:
                    break;
                case EnumScanType.NoReferenceResource:
                    prefix = "无引用资源查找_";
                    break;
                case EnumScanType.NoOriginalFileResource:
                    prefix = "无原始资源查找_";
                    break;
            }
            switch (resType)
            {
                case EnumResType.Invalid:
                    return prefix + "Check_Result_Invalid.csv";
                case EnumResType.All:
                    return prefix + "Check_Result_All_" + time + ".csv";
                case EnumResType.Texture:
                    return prefix + "Check_Result_Texture_" + time + ".csv";
                case EnumResType.Effect:
                    return prefix + "Check_Result_Effect_" + time + ".csv";
                case EnumResType.Animation:
                    return prefix + "Check_Result_Animation_" + time + ".csv";
            }
            return "Check_Result_Invalid.csv";
        }

        #endregion

        #region 字符串查找

        /// <summary>
        /// 简单查找字符串.
        /// </summary>
        private void BTN_Simple_Search_Click(object sender, EventArgs e)
        {
            if (!CheckRamData())
            {
                return;
            }
            bool haveTitle = false;
            string searchText = T_Search.Text.ToLower();
            foreach (var kv in _dstContents)
            {

                if (kv.Value.Contains(searchText))
                {
                    if (!haveTitle)
                    {
                        LogUtility.AddToLog("简单查找结果：" + searchText);
                        haveTitle = true;
                    }
                    LogUtility.AddToLog(kv.Key);
                }
            }
            if (haveTitle)
            {
                LogUtility.AddToLog("-----------------------------------------");
            }
            else
            {
                LogUtility.AddToLog("简单查找没有结果：" + searchText);
            }
        }

        /// <summary>
        /// 对字符串进行处理后再进行检查。
        /// </summary>
        private void BTN_Search_Click(object sender, EventArgs e)
        {
            if (!CheckRamData())
            {
                return;
            }
            bool haveTitle = false;
            string fileName = T_Search.Text.ToLower();
            if (fileName.EndsWith("h3dmanifest"))
            {
                LogUtility.AddToLog("不支持查找h3dmanifest文件！！！");
                return;
            }
            ResFileInfo rfi = new ResFileInfo();
            rfi.Init(fileName);

            if (FilterConfigUtility.IsIgnore(rfi))
            {
                if (!haveTitle)
                {
                    LogUtility.AddToLog("匹配查找结果：" + fileName);
                    haveTitle = true;
                }
                LogUtility.AddToLog("filter.csv中包含此字符串！");
            }
            else
            {
                foreach (var kv in _dstContents)
                {
                    if (kv.Value.Contains(rfi.Name))
                    {
                        if (!haveTitle)
                        {
                            LogUtility.AddToLog("匹配查找结果：" + fileName);
                            haveTitle = true;
                        }
                        LogUtility.AddToLog(kv.Key);
                        continue;
                    }
                    if (rfi.ProcessdName != "" && kv.Value.Contains(rfi.ProcessdName))
                    {
                        if (!haveTitle)
                        {
                            LogUtility.AddToLog("匹配查找结果：" + fileName);
                            haveTitle = true;
                        }
                        LogUtility.AddToLog(kv.Key);
                        continue;
                    }
                }
            }
            
            if (haveTitle)
            {
                LogUtility.AddToLog("-----------------------------------------");
            }
            else
            {
                LogUtility.AddToLog("匹配查找没有结果：" + fileName);
            }
        }

        #endregion

        #region P4单个文件操作

        /// <summary>
        /// P4操作文件路径.
        /// </summary>
        private void T_P4_TextChanged(object sender, EventArgs e)
        {
            _p4FilePath = T_P4Text.Text;
        }

        /// <summary>
        /// 更新文件按钮.
        /// </summary>
        private void BTN_SyncP4_Click(object sender, EventArgs e)
        {
            if (!CheckP4FileExist(_p4FilePath, _singleP4FileType))
            {
                return;
            }
            P4Utility.SyncP4(_p4FilePath);
        }

        /// <summary>
        /// 添加文件按钮.
        /// </summary>
        private void BTN_AddP4_Click(object sender, EventArgs e)
        {
            if (!CheckP4FileExist(_p4FilePath, _singleP4FileType))
            {
                return;
            }
            P4Utility.AddP4(_p4FilePath);
        }

        /// <summary>
        /// 删除文件按钮.
        /// </summary>
        private void BTN_DeleteP4_Click(object sender, EventArgs e)
        {
            if (CheckP4FileExist(_p4FilePath, _singleP4FileType))
            {
                P4Utility.DeleteP4(_p4FilePath);
//                return;
            }
//            P4Utility.DeleteP4(_p4FilePath);
            DeleteOtherFile(_p4FilePath);

            // 删除android对应的iOS资源.
            if (_p4FilePath.Contains(@"ResourcePublish\CDN\SourceFiles\android\"))
            {
                string iosFilePath = _p4FilePath.Replace(@"\android\", @"\iOS\");
                if (File.Exists(iosFilePath))
                {
                    P4Utility.DeleteP4(iosFilePath);
                }
                DeleteOtherFile(iosFilePath);
            }

            // 删除iOS对应的android资源.
            if (_p4FilePath.Contains(@"ResourcePublish\CDN\SourceFiles\iOS\"))
            {
                string androidFilePath = _p4FilePath.Replace(@"\iOS\", @"\android\");
                if (File.Exists(androidFilePath))
                {
                    P4Utility.DeleteP4(androidFilePath);
                }
                DeleteOtherFile(androidFilePath);
            }
        }

        private void DeleteOtherFile(string filePath)
        {
            // 删除ab包对应的manifest配置文件.
            string manifestFilePath = FileUtility.GetH3DManifestFilePath(filePath);
            if (!string.IsNullOrEmpty(manifestFilePath))
            {
                P4Utility.DeleteP4(manifestFilePath);
            }

            // 删除原始资源对应的.meta文件.
            string mateFileName = FileUtility.GetMetaFilePath(filePath);
            if (!string.IsNullOrEmpty(mateFileName))
            {
                P4Utility.DeleteP4(mateFileName);
            }

            // 删除表情以及表情相关文件.
            string expressionFilePath = FileUtility.GetExpressionFromActionFilePath(filePath);
            if (!string.IsNullOrEmpty(expressionFilePath))
            {
                P4Utility.DeleteP4(expressionFilePath);
                DeleteOtherFile(expressionFilePath);
            }
        }

        /// <summary>
        /// 提交到P4服务器.
        /// </summary>
        private void BTN_SubmitP4_Click(object sender, EventArgs e)
        {
            P4Utility.SubmitAllChange(_p4FilePath);
        }

        /// <summary>
        /// p4操作单个文件,选择文件类型.
        /// </summary>
        private void SingleP4ToggleButton_OnChecked(object sender, RoutedEventArgs e)
        {
            RadioButton radioButton = (RadioButton)sender;
            if (radioButton.IsChecked != null && radioButton.IsChecked == true)
            {
                _singleP4FileType = (EnumP4FileType)Int32.Parse(radioButton.Tag.ToString());
            }
        }

        /// <summary>
        /// 判断p4操作文件或者目录是否存在.
        /// </summary>
        private bool CheckP4FileExist(string filePath, EnumP4FileType fileType)
        {
            switch (fileType)
            {
                case EnumP4FileType.FileType:
                    if (File.Exists(filePath))
                    {
                        return true;
                    }
                    break;
                case EnumP4FileType.DirectorType:
                    if (Directory.Exists(filePath))
                    {
                        return true;
                    }
                    break;
            }
            LogUtility.AddToLog("操作文件或者目录不存在！！！");
            return false;
        }

        #endregion

        #region P4批量操作

        /// <summary>
        /// 读取CSV文件并且删除文件中的文件.
        /// </summary>
        private void BTN_DeleteP4ByCSV_Click(object sender, EventArgs e)
        {
            string csvFilePath = FileUtility.GetConfigFilePath(T_P4SVCText.Text);
            if (string.IsNullOrEmpty(csvFilePath))
            {
                LogUtility.AddToLog("配置文件不存在：" + csvFilePath);
                return;
            }
            string[] csvStrings = FileReaderWriterUtility.ReadFile(csvFilePath, Encoding.Default);
            for (int i = 0; i < csvStrings.Length; i++)
            {
                string[] fileStrings = csvStrings[i].Split(',');
                for (int j = 0; j < fileStrings.Length; j++)
                {
                    string filePath = fileStrings[j];
                    if (File.Exists(filePath))
                    {
                        // 删除源文件.
                        P4Utility.DeleteP4(filePath);
                    }
                    // 删除ab包对应的manifest配置文件.
                    DeleteOtherFile(filePath);
                    // 删除android对应的iOS资源.
                    if (filePath.Contains(@"ResourcePublish\CDN\SourceFiles\android\"))
                    {
                        string iosFilePath = filePath.Replace(@"\android\", @"\iOS\");
                        if (File.Exists(iosFilePath))
                        {
                            P4Utility.DeleteP4(iosFilePath);
                        }
                        DeleteOtherFile(iosFilePath);
                    }

                    // 删除iOS对应的android资源.
                    if (filePath.Contains(@"ResourcePublish\CDN\SourceFiles\iOS\"))
                    {
                        string androidFilePath = filePath.Replace(@"\iOS\", @"\android\");
                        if (File.Exists(androidFilePath))
                        {
                            P4Utility.DeleteP4(androidFilePath);
                        }
                        DeleteOtherFile(androidFilePath);
                    }
                }
            }
        }

        #endregion

        #region 读取资源到RAM

        /// <summary>
        /// 预设路径Text变化事件.
        /// </summary>
        private void T_UIPefabPath_TextChanged(object sender, EventArgs e)
        {
            _pathConfigData.m_UIPrefabPath = T_UIPefabPath.Text;
        }

        /// <summary>
        /// 脚本路径Text变化事件.
        /// </summary>
        private void T_ScriptsPath_TextChanged(object sender, EventArgs e)
        {
            _pathConfigData.m_ScriptsPath = T_ScriptsPath.Text;
        }

        /// <summary>
        /// 服务器资源路径Text变化事件.
        /// </summary>
        private void T_ServerPath_TextChanged(object sender, EventArgs e)
        {
            _pathConfigData.m_ServerCfgPath = T_ServerPath.Text;
        }

        /// <summary>
        /// 客户端资源路径Text变化事件.
        /// </summary>
        private void T_ClientPath_TextChanged(object sender, EventArgs e)
        {
            _pathConfigData.m_ClientCfgPath = T_ClientPath.Text;
        }

        /// <summary>
        /// 读取按钮点击事件.
        /// </summary>
        private void BTN_Load_Click(object sender, EventArgs e)
        {
            try
            {
                FilterConfigUtility.ReadFilter();
                RegexConfigUtility.Reload();
                SuffixConfigUtility.Reload();
                List<string> dstRootPaths = new List<string>();
                // 检查预设路径配置.
                if (string.IsNullOrEmpty(_pathConfigData.m_UIPrefabPath))
                {
                    LogUtility.AddToLog(T_UIPrefabPath_Tip.Content + "路径为空！");
                }
                else
                {
                    dstRootPaths.Add(_pathConfigData.m_UIPrefabPath);
                }
                // 检查脚本路径配置.
                if (string.IsNullOrEmpty(_pathConfigData.m_ScriptsPath))
                {
                    LogUtility.AddToLog(T_ScriptsPath_Tip.Content + "路径为空！");
                }
                else
                {
                    dstRootPaths.Add(_pathConfigData.m_ScriptsPath);
                }
                // 检查服务器路径配置.
                if (string.IsNullOrEmpty(_pathConfigData.m_ServerCfgPath))
                {
                    LogUtility.AddToLog(T_ServerPath_Tip.Content + "路径为空！");
                }
                else
                {
                    dstRootPaths.Add(_pathConfigData.m_ServerCfgPath);
                }
                // 检查客户端路径配置.
                if (string.IsNullOrEmpty(_pathConfigData.m_ClientCfgPath))
                {
                    LogUtility.AddToLog(T_ClientPath_Tip.Content + "路径为空！");
                }
                else
                {
                    dstRootPaths.Add(_pathConfigData.m_ClientCfgPath);
                }

                _dstContents.Clear();
                foreach (var dstRootPath in dstRootPaths)
                {
                    ReadFileToRam(dstRootPath, _dstContents);
                }
//                ReadFileToRam(_newActivityPath, _activityDstContents);
                LogUtility.AddToLog("缓存成功！");
            }
            catch (Exception exception)
            {
                LogUtility.AddToLog("功能无法正常使用！！！");
                LogUtility.AddToLog(exception.StackTrace);
                Console.WriteLine(exception);
            }
        }

        /// <summary>
        /// 缓存目录下的所有文件.
        /// </summary>
        private void ReadFileToRam(string rootFilePath, Dictionary<string, string> dstDic)
        {
            try
            {
                if (Directory.Exists(rootFilePath))
                {
                    string[] files = Directory.GetFiles(rootFilePath, "*", SearchOption.AllDirectories);
                    foreach (string f in files)
                    {
                        dstDic[f] = File.ReadAllText(f).ToLower();
                    }
                }
                else
                {
                    LogUtility.AddToLog("找不到路径：" + rootFilePath);
                }
            }
            catch (Exception e)
            {
                LogUtility.AddToLog("缓存路径文件错误：" + rootFilePath);
                LogUtility.AddToLog(e.StackTrace);
                Console.WriteLine(e);
                throw;
            }
            
        }

        /// <summary>
        /// 检查RAM中是否有数据.
        /// </summary>
        /// <returns></returns>
        private bool CheckRamData()
        {
            if (_dstContents.Count == 0)
            {
                LogUtility.AddToLog("请先将数据读入RAM！！！");
                return false;
            }

            return true;
        }
        #endregion

        #region Log相关

        /// <summary>
        /// 清空Log
        /// </summary>
        private void BTN_ClearLog_OnClick(object sender, RoutedEventArgs e)
        {
            LogUtility.ClearLog();
        }

        /// <summary>
        /// Log选中操作.
        /// </summary>
        private void LogFrame_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender != null && ((ListBox)sender).SelectedItem != null)
            {
                selText.Text = ((ListBox)sender).SelectedItem.ToString();
            }
        }

        #endregion

        private void BTN_Test_OnClick(object sender, RoutedEventArgs e)
        {
            string currentDirectory = Directory.GetCurrentDirectory();
            LogUtility.AddToLog(currentDirectory);
            LogUtility.AddToLog(Environment.CurrentDirectory);
            string exePath = Assembly.GetEntryAssembly().Location;
            LogUtility.AddToLog(exePath);
            string exeDir = System.IO.Path.GetDirectoryName(exePath);
            LogUtility.AddToLog(exeDir);
            DirectoryInfo binDir = System.IO.Directory.GetParent(exeDir);
            LogUtility.AddToLog(binDir.Name);
            LogUtility.AddToLog(Directory.GetParent(Environment.CurrentDirectory).Parent.FullName);
            LogUtility.AddToLog(System.IO.Path.GetFullPath(@"..\..\..\"));
        }

        /// <summary>
        /// 写入到CSV中
        /// </summary>
        private void BTN_Output_To_SVC(object sender, EventArgs e)
        {
            string temppath = _resFileSourcePath;
            LogUtility.AddToLog(System.DateTime.Now.ToShortTimeString() + temppath + System.Environment.NewLine);
            string musicActPath =
                "G:\\x5_mobile\\x5_mobile\\mr\\Resources\\ResourcePublish\\CDN\\SourceFiles\\android\\assetbundles\\texture\\musicact\\skill_110101001_iocn_mat";
            LogUtility.AddToLog(System.DateTime.Now.ToShortTimeString() + musicActPath + System.Environment.NewLine);
            if (musicActPath.Contains(_resFilePath))
            {
                string relativePath = musicActPath.Remove(0, _resFilePath.Length);
                LogUtility.AddToLog(System.DateTime.Now.ToShortTimeString() + relativePath + System.Environment.NewLine);
                temppath += relativePath;
            }

            if (temppath.EndsWith("_mat"))
            {
                temppath = temppath.Remove(temppath.Length - 4, 4);
            }


            if (File.Exists(temppath + ".png"))
            {
                temppath += ".png";
                LogUtility.AddToLog(System.DateTime.Now.ToShortTimeString() + "存在源文件" + System.Environment.NewLine);
                string fileSize = FileReaderWriterUtility.GetFileSize(temppath);
                LogUtility.AddToLog(System.DateTime.Now.ToShortTimeString() + "源文件大小为：" + fileSize + ", " + System.Environment.NewLine);
            }
            if (File.Exists(temppath + ".jpg"))
            {
                temppath += ".jpg";
                LogUtility.AddToLog(System.DateTime.Now.ToShortTimeString() + "存在源文件" + System.Environment.NewLine);
                string fileSize = FileReaderWriterUtility.GetFileSize(temppath);
                LogUtility.AddToLog(System.DateTime.Now.ToShortTimeString() + "源文件大小为：" + fileSize + ", " + System.Environment.NewLine);
            }
            else
            {
                LogUtility.AddToLog(System.DateTime.Now.ToShortTimeString() + "不存在源文件" + System.Environment.NewLine);
            }
            string[] strs = new[] { "ab路径", "texture路径", "ab资源大小" };
            List<string[]> strList = new List<string[]>();
            strList.Add(strs);

            if (FileReaderWriterUtility.WriteToCSV(GetOutPutCSVFileName(EnumScanType.NoReferenceResource, EnumResType.Texture), strList))
            {
                LogUtility.AddToLog("写入csv失败！！！");
            }
        }
    }
}